<template>
  <div class="system-settings-container">
    <div class="page-header">
      <el-button @click="goBack" text>
        <el-icon><ArrowLeft /></el-icon>
        返回系统管理
      </el-button>
      <h1>系统设置</h1>
      <p>管理系统全局配置和参数</p>
    </div>

    <div class="settings-sections">
      <!-- 基础设置 -->
      <el-card class="settings-card">
        <template #header>
          <div class="card-header">
            <el-icon><Setting /></el-icon>
            <h3>基础设置</h3>
          </div>
        </template>

        <el-form label-width="150px" class="settings-form">
          <el-form-item label="系统名称">
            <el-input v-model="systemSettings.name" placeholder="茶叶溯源系统" />
          </el-form-item>

          <el-form-item label="系统描述">
            <el-input
              v-model="systemSettings.description"
              type="textarea"
              :rows="3"
              placeholder="基于区块链的茶叶溯源系统"
            />
          </el-form-item>

          <el-form-item label="联系邮箱">
            <el-input v-model="systemSettings.contactEmail" placeholder="admin@teatrace.com" />
          </el-form-item>

          <el-form-item label="系统版本">
            <el-input v-model="systemSettings.version" disabled />
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 区块链设置 -->
      <el-card class="settings-card">
        <template #header>
          <div class="card-header">
            <el-icon><Link /></el-icon>
            <h3>区块链设置</h3>
          </div>
        </template>

        <el-form label-width="150px" class="settings-form">
          <el-form-item label="网络类型">
            <el-select v-model="blockchainSettings.network" placeholder="请选择网络">
              <el-option label="以太坊主网" value="mainnet" />
              <el-option label="Sepolia测试网" value="sepolia" />
              <el-option label="本地开发网" value="localhost" />
            </el-select>
          </el-form-item>

          <el-form-item label="RPC节点">
            <el-input v-model="blockchainSettings.rpcUrl" placeholder="https://..." />
          </el-form-item>

          <el-form-item label="合约地址">
            <el-input v-model="blockchainSettings.contractAddress" placeholder="0x..." />
          </el-form-item>

          <el-form-item label="Gas费用限制">
            <el-input-number v-model="blockchainSettings.gasLimit" :min="21000" :max="1000000" />
          </el-form-item>

          <el-form-item label="启用区块链">
            <el-switch v-model="blockchainSettings.enabled" />
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 安全设置 -->
      <el-card class="settings-card">
        <template #header>
          <div class="card-header">
            <el-icon><Lock /></el-icon>
            <h3>安全设置</h3>
          </div>
        </template>

        <el-form label-width="150px" class="settings-form">
          <el-form-item label="密码策略">
            <el-select v-model="securitySettings.passwordPolicy">
              <el-option label="简单 (6位以上)" value="simple" />
              <el-option label="中等 (8位+数字)" value="medium" />
              <el-option label="复杂 (8位+数字+特殊字符)" value="complex" />
            </el-select>
          </el-form-item>

          <el-form-item label="登录失败限制">
            <el-input-number v-model="securitySettings.maxLoginAttempts" :min="3" :max="10" />
          </el-form-item>

          <el-form-item label="会话超时 (分钟)">
            <el-input-number v-model="securitySettings.sessionTimeout" :min="15" :max="480" />
          </el-form-item>

          <el-form-item label="启用验证码">
            <el-switch v-model="securitySettings.enableCaptcha" />
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 文件上传设置 -->
      <el-card class="settings-card">
        <template #header>
          <div class="card-header">
            <el-icon><Upload /></el-icon>
            <h3>文件上传设置</h3>
          </div>
        </template>

        <el-form label-width="150px" class="settings-form">
          <el-form-item label="最大文件大小 (MB)">
            <el-input-number v-model="uploadSettings.maxFileSize" :min="1" :max="100" />
          </el-form-item>

          <el-form-item label="允许的文件类型">
            <el-checkbox-group v-model="uploadSettings.allowedTypes">
              <el-checkbox label="jpg">JPG</el-checkbox>
              <el-checkbox label="png">PNG</el-checkbox>
              <el-checkbox label="pdf">PDF</el-checkbox>
              <el-checkbox label="doc">DOC</el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item label="存储路径">
            <el-input v-model="uploadSettings.storagePath" />
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 邮件设置 -->
      <el-card class="settings-card">
        <template #header>
          <div class="card-header">
            <el-icon><Message /></el-icon>
            <h3>邮件设置</h3>
          </div>
        </template>

        <el-form label-width="150px" class="settings-form">
          <el-form-item label="SMTP服务器">
            <el-input v-model="emailSettings.smtpHost" placeholder="smtp.gmail.com" />
          </el-form-item>

          <el-form-item label="SMTP端口">
            <el-input-number v-model="emailSettings.smtpPort" :min="25" :max="587" />
          </el-form-item>

          <el-form-item label="发件人邮箱">
            <el-input v-model="emailSettings.fromEmail" placeholder="noreply@teatrace.com" />
          </el-form-item>

          <el-form-item label="启用SSL">
            <el-switch v-model="emailSettings.enableSSL" />
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" @click="saveSettings" :loading="saving">
          保存设置
        </el-button>
        <el-button @click="resetSettings">
          重置设置
        </el-button>
        <el-button type="danger" @click="restoreDefaults">
          恢复默认
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { apiMethods } from '@/api'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowLeft, 
  Setting, 
  Link, 
  Lock,
  Upload, 
  Message 
} from '@element-plus/icons-vue'

const router = useRouter()

// 状态
const saving = ref(false)

// 设置表单数据
const systemSettings = reactive({
  name: '茶叶溯源系统',
  description: '基于区块链的茶叶全生命周期溯源管理系统',
  contactEmail: 'admin@teatrace.com',
  version: '1.0.0'
})

const blockchainSettings = reactive({
  network: 'sepolia',
  rpcUrl: 'http://localhost:8545',
  contractAddress: '',
  gasLimit: 200000,
  enabled: false
})

const securitySettings = reactive({
  passwordPolicy: 'medium',
  maxLoginAttempts: 5,
  sessionTimeout: 120,
  enableCaptcha: false
})

const uploadSettings = reactive({
  maxFileSize: 10,
  allowedTypes: ['jpg', 'png', 'pdf'],
  storagePath: '/uploads'
})

const emailSettings = reactive({
  smtpHost: '',
  smtpPort: 587,
  fromEmail: '',
  enableSSL: true
})

// 方法
const goBack = () => {
  router.push('/users')
}

const saveSettings = async () => {
  try {
    saving.value = true

    const settings = {
      system: systemSettings,
      blockchain: blockchainSettings,
      security: securitySettings,
      upload: uploadSettings,
      email: emailSettings
    }

    // 这里应该调用实际的保存API
    // await apiMethods.admin.updateSystemSettings(settings)

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    ElMessage.success('系统设置保存成功')
  } catch (error) {
    console.error('保存系统设置失败:', error)
    ElMessage.error('保存设置失败，请重试')
  } finally {
    saving.value = false
  }
}

const resetSettings = () => {
  // 重置为初始状态
  ElMessage.info('设置已重置')
}

const restoreDefaults = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要恢复所有设置到默认值吗？此操作不可撤销。',
      '确认恢复默认设置',
      { type: 'warning' }
    )

    // 恢复默认设置
    systemSettings.name = '茶叶溯源系统'
    systemSettings.description = '基于区块链的茶叶全生命周期溯源管理系统'
    systemSettings.contactEmail = 'admin@teatrace.com'
    
    blockchainSettings.network = 'sepolia'
    blockchainSettings.rpcUrl = 'http://localhost:8545'
    blockchainSettings.contractAddress = ''
    blockchainSettings.gasLimit = 200000
    blockchainSettings.enabled = false
    
    securitySettings.passwordPolicy = 'medium'
    securitySettings.maxLoginAttempts = 5
    securitySettings.sessionTimeout = 120
    securitySettings.enableCaptcha = false
    
    uploadSettings.maxFileSize = 10
    uploadSettings.allowedTypes = ['jpg', 'png', 'pdf']
    uploadSettings.storagePath = '/uploads'
    
    emailSettings.smtpHost = ''
    emailSettings.smtpPort = 587
    emailSettings.fromEmail = ''
    emailSettings.enableSSL = true

    ElMessage.success('已恢复默认设置')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('恢复默认设置失败')
    }
  }
}

// 生命周期
onMounted(async () => {
  try {
    // 加载现有设置
    // const response = await apiMethods.admin.getSystemSettings()
    // if (response.data.success) {
    //   Object.assign(systemSettings, response.data.data.system)
    //   Object.assign(blockchainSettings, response.data.data.blockchain)
    //   // ... 其他设置
    // }
  } catch (error) {
    console.error('加载系统设置失败:', error)
  }
})
</script>

<style scoped>
.system-settings-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h1 {
  color: #2c3e50;
  margin: 10px 0;
}

.page-header p {
  color: #606266;
  font-size: 14px;
}

.settings-sections {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.settings-card {
  width: 100%;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-header h3 {
  margin: 0;
  color: #2c3e50;
}

.settings-form {
  max-width: 600px;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
  margin-top: 30px;
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
}

@media (max-width: 768px) {
  .system-settings-container {
    padding: 10px;
  }

  .action-buttons {
    flex-direction: column;
  }

  .settings-form {
    max-width: none;
  }
}
</style>